<?php

namespace App\Admin\Http\Controllers\Business;

use App\Admin\Eloquent\User;
use App\Admin\Eloquent\UserInfo;
use App\Admin\Http\Controllers\Controller;
use App\Eloquent\RoleUser;
use App\Http\Controllers\Utils\UtilsController;
use DB;
use Ibeibeili\SinaPay\Facades\SetRealName;
use Illuminate\Http\Request;
use Laracasts\Flash\Flash;
use Ibeibeili\SinaPay\Facades\CreateActivateMember;
use Symfony\Component\HttpKernel\Exception\HttpException;
use UnbindingVerify;
use BindingVerify;
use App\Admin\Eloquent\Code;
use Mockery\CountValidator\Exception;
use ModifyVerifyMobile;
use Hash;

/**
 * 用户管理控制器
 *
 * Class UsersController
 * @package App\Admin\Http\Controllers\Business
 */
class UsersController extends Controller
{
    /**
     * UsersController constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function index(Request $request,string $download = '')
    {
        $query = $request->only('name', 'id_card', 'userKey', 'is_set_pay_password','id_card','is_set_phone','is_set_bankcard','is_set_bankcard','p_start_at', 'p_end_at');
        $query['download'] = $download;

        $users = User::paging_query($query);

        if (!empty($query))
            $users = $users->appends($query);

        $links = $users->render();

        return view('admin.business.user.index', compact('query', 'users', 'links'));
    }

    public function create()
    {
        return view('admin.business.user.create');
    }

    public function store(Request $request)
    {
        User::saveFront($request->all());
        Flash::success("保存用户信息成功");
                        return $this->redirectAction('Business\UsersController@index',['download'=>'-']);
    }

    /**
     * 修改用户信息表单
     *
     * @param int $id
     * @return mixed
     */
    public function edit(int $id)
    {
        $user = User::findOrFail($id);

        if ($user->scope != "front")
            abort(404);

        return view('admin.business.user.edit', compact('user'));
    }

    /**
     *
     * 修改指定用户信息
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, int $id)
    {

        $userParameter = $this->getUserParameter($request);

        $userInfoParameter = $this->getUserInfoParameter($request);

        //处理密码
        if (isset($userParameter['password']) && !empty($userParameter['password'])) {
            //对密码二次加密
            $userParameter['password'] = bcrypt(md5($userParameter['password']));
        } else {
            unset($userParameter['password']);
        }

        // DB::beginTransaction();
        // try {
        
        //查找操作用户
        $user = User::findOrFail($id);

        //判断是否非法修改用户名
        if (isset($userParameter['username'])) {      //如果存在修改用户名的情况
            if (!empty($user->username)) {            //如果用户名已经生成
                unset($userParameter['username']);  //不能非法修改用户名
            }
        }

            //用户手机号码认证状态
            $phone_number_verified = $user->phone_number_verified;

            //用户邮箱号码认证状态
            $email_verified = $user->email_verified;

            //更新用户基本信息
            // $user->update($userParameter);

            //认证手机号码
            // $userInfoParameter['user_id'] = $user->id;
            // dd($userParameter);

            $email = @$userParameter['email'];
            unset($userParameter['email']);

            $phone_number = @$userParameter['phone_number'];
            unset($userParameter['phone_number']);

            DB::beginTransaction();
            try {
                //解绑邮箱
                if($email_verified == 1){
                    $userParameter['email_verified'] = 0;
                    $userParameter['email'] = null;
                    $user->update($userParameter);
                //解绑邮箱信息
                $result = UnbindingVerify::send(['identity_id' => $user->identity_id, 'identity_type' => 'UID', 'verify_type' => 'EMAIL' ]);
                    if($result['response_code'] != 'APPLY_SUCCESS'){
                        abort(600,$result['response_message']);
                    }
                    //成功执行操作
                }
                DB::commit();
            } catch (Exception $e) {
                DB::rollBack();
            }
            // dd(1);

            
            DB::beginTransaction();
            try {
                //认证邮箱
                if(!empty($email)){
                    $userParameter['email_verified'] = 1;
                    $userParameter['email'] = $email;
                    //修改邮箱
                    $user->update($userParameter);
                    $result = BindingVerify::send(['identity_id' => $user->identity_id, 'identity_type' => 'UID', 'verify_entity' => $email, 'verify_type' => 'EMAIL']);
                    if($result['response_code'] != 'APPLY_SUCCESS'){
                        abort(600,$result['response_message']);
                    }
                }
                DB::commit();
            } catch (Exception $e) {
                DB::rollBack();
            }

            DB::beginTransaction();
            try {
                //解绑手机号码
                if($phone_number_verified == 1 && !$user->isSetPayPassword()){
                    $userParameter['phone_number_verified'] = 0;
                    $userParameter['phone_number'] = null;
                    $user->update($userParameter);
                    //解绑手机号码
                    $result = UnbindingVerify::send(['identity_id' => $user->identity_id, 'identity_type' => 'UID', 'verify_type' => 'MOBILE' ]);
                    if($result['response_code'] != 'APPLY_SUCCESS'){
                        abort(600,$result['response_message']);
                    }
                }
                DB::commit();
            } catch (Exception $e) {
                DB::rollBack();
            }

            DB::beginTransaction();
            try {
                //认证手机号码
                if(!empty($phone_number) && !$user->isSetPayPassword()){
                    $userParameter['phone_number_verified'] = 1;
                    $userParameter['phone_number'] = $phone_number;
                    $user->update($userParameter);

                    $result = BindingVerify::send(['identity_id' => $user->identity_id, 'identity_type' => 'UID', 'verify_entity' => $phone_number, 'verify_type' => 'MOBILE' ]);
                    if($result['response_code'] != 'APPLY_SUCCESS'){
                        abort(600,$result['response_message']);
                    }

                }
                DB::commit();
            } catch (Exception $e) {
                DB::rollback();
            }

            //修改手机号码


            Flash::success("修改用户信息成功");
                        return $this->redirectAction('Business\UsersController@index',['download'=>'-']);
        // } catch (\Exception $e) {
        //     DB::rollBack();
        //     throw $e;
            
        // }

    }

    /**
     * 查看用户详情
     *
     * @param int $id
     * @return mixed
     */
    public function show(int $id)
    {
        $user = User::findOrFail($id);
        $broker_mame=UserInfo::where('invite_code','=',$user->userInfo->broker_code)->value('name');
        //查询用户所在部门名称
        // $dept_name = (Code::where('parent_code', '=', $user->userInfo->org_code)->where('type_id', '=', 'DEPARTMENT')->where('code', '=', $user->dept_code)->first())->name;
        // return $dept_name;
        return view('admin.business.user.show', compact('user','broker_mame'));
    }

    public function destroy(int $id)
    {
        $user = User::findOrFail($id);

        DB::beginTransaction();
        try {
            $userInfo = $user->userInfo;

            RoleUser::where('user_id', $user->id)->delete();

            $userInfo->delete();

            $user->delete();


            DB::commit();

            Flash::success("删除用户信息成功");

                        return $this->redirectAction('Business\UsersController@index',['download'=>'-']);
        } catch (\Exception $e) {
            DB::rollBack();
            Flash::error("删除用户信息失败!");

                        return $this->redirectAction('Business\UsersController@index',['download'=>'-']);
        }
    }

    /**
     * 解锁用户状态
     * 
     * @return [type] [description]
     */
    public function unlock(int $user_id){

        User::findOrFail($user_id)->unlock();

        Flash::success('用户解锁成功!');
                        return $this->redirectAction('Business\UsersController@index',['download'=>'-']);
    }

    /**
     * 获取用户信息表所需参数
     *
     * @param Request $request
     * @return array|string
     */
    public function getUserInfoParameter(Request $request)
    {
        return $request->only('recommended');
    }

    /**
     * 获取用户表所需参数
     *
     * @param Request $request
     * @return array|string
     */
    public function getUserParameter(Request $request)
    {
        $args = $request->only('username', 'password', 'phone_number', 'email');
        foreach ($args as $key => $value) {
            if (empty($value) && $key != 'phone_number') {
                unset($args[$key]);
            }
        }
        return $args;
    }
    public function setRealName(int $id){
        return view('admin.business.user.set_real_name',compact('id'));
    }

    public function saveRealName(Request $request, int $id)
    {
        DB::beginTransaction();
        try {
            //获取请求参数
            $query = $request->only('name', 'id_card');
            $query['name_verified'] = 1;                    //设置已实名认证
            $user = User::findOrFail($id);
            $user->userInfo->update($query);

            //sina实名认证
            $args['real_name'] = $query['name'];
            $args['cert_no'] = $query['id_card'];
            $args['identity_id'] = $user->identity_id;

            $result = SetRealName::send($args);
            if($result['response_code']!='APPLY_SUCCESS'){
                abort(600,$result['response_message']);
            }
            DB::commit();
            Flash::success("用户实名认证成功");
                        return $this->redirectAction('Business\UsersController@index',['download'=>'-']);
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }
    /**
     * 变更经纪人/营销机构
     * 
     * @return [type] [description]
     */
    public function changeBroker(){
        //查询所有的营销机构
        $orgs = DB::table('organizational_users as a')
            ->join('role_user as b', 'a.user_id', '=', 'b.user_id')
            ->join('codes as c', 'a.code', '=', 'c.code')
            ->join('roles as d', 'b.role_id', '=', 'd.id')
            ->where('d.slug', '=', 'MarketingAgency')
            ->select('a.company_name', 'a.code', 'c.description')
            ->get();

        return view('admin.business.user.change_broker',compact('orgs'));
    }
    /**
     * 处理变更经纪人/营销机构
     * @param  Request     $request [description]
     * @param  int|integer $id      [description]
     * @return [type]               [description]
     */
    public function saveChangeBroker(Request $request,int $id = 0){
        switch ($id) {  

            case 0: //处理投资人变更经纪人
                    
                    $username = $request->input('username');
                    $jjrname = $request->input('jjrname');
                    
                    //查询投资人是否存在
                    $user = User::where('username', $username)
                        ->orWhere('email', $username)
                        ->orWhere('phone_number', $username)
                        ->first();
                    if(empty($user)||!$user->hasRole('User')||$user->hasRole(['Agent','OperatingPlatform','Loaner','GuaranteeAgency','MarketingAgency'])){
                        abort(600,'投资人用户不存在...');
                    }

                    //查询经纪人是否存在//查询投资人是否存在
                    $user2 = User::where('username', $jjrname)
                        ->orWhere('email', $jjrname)
                        ->orWhere('phone_number', $jjrname)
                        ->first();
                    if(empty($user2)||!$user2->hasRole('Agent')){
                        abort(600,'经纪人不存在...');
                    }

                    //数据校验正确,开始执行经纪人变更操作    
                    $user->userInfo->broker_code = $user2->userInfo->invite_code;   //变更经纪人
                    $user->userInfo->org_code = $user2->userInfo->org_code;         //变更为经纪人机构
                    $user->userInfo->dept_code = $user2->userInfo->dept_code;       //变更未经纪人所属部门
                    $user->userInfo->save();

                    Flash::success("经纪人变更成功!");
                        return $this->redirectAction('Business\UsersController@index',['download'=>'-']);
                break;
                case 1:
                    $jjrname = $request->input('jjrname');
                    $org_code = $request->input('org_code');
                    $dept_no = $request->input('dept_no');

                    //查询经纪人是否存在
                    $user = User::where('username', $jjrname)
                        ->orWhere('email', $jjrname)
                        ->orWhere('phone_number', $jjrname)
                        ->first();

                    if(empty($user)||!$user->hasRole('Agent')){
                        abort(600,'经纪人不存在...');
                    }
                    $user->userInfo->update(['org_code' => $org_code, 'dept_code' =>$dept_no]);

                    Flash::success("经纪人营销部门变更成功!");
                        return $this->redirectAction('Business\UsersController@index',['download'=>'-']);
                break;
                case 2:

                    
                    $username = $request->input('username');
                    $org_code = $request->input('org_code');
                    $dept_no = $request->input('dept_no');
                    
                    //查询投资人是否存在
                    $user = User::where('username', $username)
                        ->orWhere('email', $username)
                        ->orWhere('phone_number', $username)
                        ->first();
                    if(empty($user)||!$user->hasRole('User')||$user->hasRole(['Agent','OperatingPlatform','Loaner','GuaranteeAgency','MarketingAgency'])){
                        abort(600,'投资人用户不存在...');
                    }

                    try{
                        DB::beginTransaction();
                        //数据校验正确,执行变更操作
                        $user->userInfo->update(['dept_code' => $dept_no, 'org_code' => $org_code, 'broker_code' => $user->userInfo->invite_code]);
                        //查询投资人角色对应ID
                        $id = (DB::table('roles')->where('slug', '=', 'User')->first())->id;
                        //查询经纪人角色对应ID
                        $id2 = (DB::table('roles')->where('slug', '=', 'Agent')->first())->id;
                        //删除用户的投资人角色
                        DB::table('role_user')->where('user_id', '=', $user->id)->where('role_id', '=', $id)->delete();
                        //添加用户的经纪人角色
                        DB::insert('insert into role_user value('.$user->id.','.$id2.')');

                        DB::commit();
                        Flash::success("投资人转经纪人成功!");
                        return $this->redirectAction('Business\UsersController@index',['download'=>'-']);
                    }catch(Exception $e){
                        DB::rollback();
                        throw $e;
                        
                    }
                break;
                case 4:

                break;
            default:
                return 'error.....';
                break;
        }
    }
    /**
     * 查询营销机构下的部门列表
     * 
     * @return [type] [description]
     */
    public function orgDept(Request $request){
        $org_code = $request->input('org_code');
        $depts = Code::where('parent_code', '=', $org_code)->where('type_id', '=', 'DEPARTMENT')->get();
        return $depts;
    }

    /**
     * 强制修改用户手机号码
     * 
     * @return [type] [description]
     */
    public function modifyPhoneNumber(int $id){
        $user = User::findOrFail($id);

        $result = ModifyVerifyMobile::send([
            'identity_id' => $user->identity_id,
            'identity_type' => 'UID',
            ]);

        if($result['response_code'] != 'APPLY_SUCCESS')
            abort(600,$result['response_message']);

        return redirect($result['redirect_url']);
    }

    /**
     * 修改后台登陆用户的密码
     * 
     * @return [type] [description]
     */
    public function modifyAdminPassword(){
        $author = $this->currentUser()->username;
        return view('admin.auth.modify_password');
    }

    /**
     *  保存修改后台登陆用户的密码
     * 
     * [saveAdminPassword description]
     * @return [type] [description]
     */
    public function saveAdminPassword(Request $request){
        $user = $this->currentUser();

        $args = $request->only('oldPassword','newPassword');

        //处理原密码和新密码
        $args['oldPassword'] = md5($args['oldPassword']);
        $args['newPassword'] = md5($args['newPassword']);

        if(!Hash::check($args['oldPassword'],$user->password)){
            return abort(600,'原密码不正确');
        }

        //保存新密码
        $user->password = Hash::make($args['newPassword']);
        $user->save();

        Flash::success("修改用户密码成功");
        return $this->redirectAction('Auth\AuthController@getLogout');
    }
}